package com.scvtc.domain.dto.common;


import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.scvtc.domain.dto.system.menu.SystemMenuDto;
import com.scvtc.domain.entity.system.SystemUser;
import lombok.*;
import lombok.experimental.Accessors;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import static com.scvtc.constants.SystemConstants.STATUS_ENABLE;

/**
 * @Description: 系统登录用户
 * @Author: yiFei
 * @date: 2022/4/13 17:10
 */
@Data
@Builder
@EqualsAndHashCode(callSuper = false)
@AllArgsConstructor
@NoArgsConstructor
@Accessors(chain = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
public class SystemLoginUser implements UserDetails, Serializable {

    private static final long serialVersionUID = -96012347116778L;

    /**
     * 系统用户
     */
    private SystemUser userInfo;
    /**
     * 权限
     */
    private List<String> permissions;
    /**
     * 用户菜单
     */
    private List<SystemMenuDto> menus;

    /**
     * 写入权限
     *
     * @return
     */
    @Override
    @JsonIgnore
    public Collection<? extends GrantedAuthority> getAuthorities() {
        Collection<GrantedAuthority> authorities = new ArrayList<>();
        for (String item : this.permissions) {
            // 添加权限
            authorities.add(new SimpleGrantedAuthority(item));
        }
        return authorities;
    }

    @Override
    @JsonIgnore
    public String getPassword() {
        return userInfo.getPassword();
    }

    @Override
    @JsonIgnore
    public String getUsername() {
        return userInfo.getUserName();
    }

    @Override
    @JsonIgnore
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    @JsonIgnore
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    @JsonIgnore
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    @JsonIgnore
    public boolean isEnabled() {
        return (STATUS_ENABLE).equals(userInfo.getStatus());
    }
}
